package xdu.lz.stage2_design_pattern.chapter1_volatie.volitale;


/**
 * volatile不能保证原子性
 * 1)内存可见性
 * 2)防止重排序--happens-before原则
 */
public class VolatileTest {
    //    private static volatile   int initValue = 0;
    private static int initValue = 0;
    private static final int MAX_VALUE = 10;

    public static void main(String[] args) {
        new Thread(() -> {
            int localValue = initValue;
            //java底层“优化”：没有写操作所以一直拿cache中的数据而不去主内存中拿
            //如果要打印出当前值，则会去内存中拿
            //如果休眠哪怕是1us,CPU认为有空余时间，也会去主内存中拿
            while (localValue < MAX_VALUE) {
                if (localValue != initValue) {
                    System.out.println(Thread.currentThread().getName() + "the value updated to " +
                            "" + initValue);
                    localValue = initValue;

                }

                /*System.out.println("localValue = " + localValue);
                System.out.println("initValue = " + initValue);
                try {
                    Thread.sleep(0,1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/
            }
        }, "read -thread").start();
        try {
            Thread.sleep(10L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            int localValue = initValue;
            while (localValue < MAX_VALUE) {
                System.out.println(Thread.currentThread().getName() + "update the value to " +
                        (++localValue));
                initValue = localValue;
                try {
                    Thread.sleep(100L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "write -thread").start();

    }
}
